<script lang="ts">
import { defineComponent } from 'vue'
const { t } = useI18n()
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { QuotationApi } from '@/api/quote/quotation'
import '@/assets/iconfont/iconfont.css'
import QuotationForm from './QuotationForm.vue'
import uploadForm from './uploadForm.vue'
import { formatDate } from '@/utils/formatTime';
import download from '@/utils/download'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { formatCurrency } from '@/utils/a_utilFunction'


enum STATUS {
  "yitongguo" = '20',
  "yibohui" = '30',
  "daishenhe" = '10',
  "daitijiao" = '0',
  "yituihui" = '50',
  "returning" = '40'
  //"returning" = '40'  合并 40跟10的状态
}
export default defineComponent({
  name: "Demo03Student",
  components: {
    QuotationForm,
    uploadForm
  },
  data() {
    return {
      router: useRouter(),
      // 遮罩层
      t,
      DICT_TYPE,
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生列表
      list: [],
      isAdmin: false,
      selected: [],
      data: [
        {
          type: 'daitijiao',
          realKey: 'draft',
          count: 0,
          status: '未提交',
        },
        {
          type: 'yituihui',
          realKey: 'returned',
          count: 0,
          status: '已退回',
        },
        {
          type: 'daishenhe',
          realKey: 'processing',
          count: 0,
          status: '待审核',
        },
        {
          type: 'yitongguo',
          realKey: 'audit',
          count: 0,
          status: '已通过',
        },
        {
          type: 'yibohui',
          realKey: 'reject',
          count: 0,
          status: '已驳回',
        },

      ] as any,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        orderDate: '',
        pageNo: 1,
        pageSize: 10,
        name: null,
        status: [] as any,
        date: null as any,
        search: null,
        description: null,
        createTime: [],
      },
      message: useMessage()
    };
  },
  created() {
    this.getList();
  },
  methods: {
    _fomatCurrency(num) {
      return formatCurrency(num)
    },
    /** 查询列表 */
    handleAdd(type: string, id?: number) {
      this.$refs.formRef.open(type, id)
    },
    _getStrDictOptions(type) {
      return getStrDictOptions(type)
    },
    async getList(search?: boolean, status?: string) {
      this.list = []
      this.isAdmin = this.judgeAdmin()
      if (search) {
        const data = await QuotationApi.getQuotationPage(Object.assign({}, this.queryParams))
        this.list = data.list
        this.total = data.total
        return;
      }
      try {
        this.loading = true;
        if (status) {
          // [10 ,40]
          this.queryParams.status = status == '10' ? ['审批中', '退回中'] : status
          this.selected = this.queryParams.status
        }
        const data = await QuotationApi.getQuotationPage(Object.assign({}, this.queryParams))
        const dataStatus = await QuotationApi.getAllStatus();

        this.list = data.list
        this.total = data.total
        let keys = Object.keys(dataStatus);
        keys.forEach((item: any) => {
          this.data.forEach((dataItem: any) => {
            if (dataItem.realKey === item) {
              dataItem.count = dataStatus[item]
            }
          })
        })
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery(reset?: boolean = false) {
      if (reset) {
        this.selected = [];
      }
      this.queryParams.status = this.selected
      this.getList(true);
    },
    resetForm() {
      this.queryParams = {
        orderDate: '',
        pageNo: 1,
        pageSize: 10,
        name: null,
        status: [] as any,
        date: null as any,
        search: null,
        description: null,
        createTime: [],
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm();
      this.handleQuery(true);
    },
    /** 添加/修改操作 */
    openForm(id, row) {
      this.$refs["formRef"].open(id, row);
    },
    /** 添加/修改操作 */
    openUploadForm(type, row) {
      this.$refs["uploadRef"].open(type, row);
    },
    /** 删除按钮操作 */
    async handleDelete(id, quoteNumber) {
      try {
        // 删除的二次确认
        await this.message.delConfirm()
        // 发起删除
        await QuotationApi.deleteQuotation(id, quoteNumber)
        this.message.success(t('common.delSuccess'))
        // 刷新列表
        await this.getList()
      } catch { }
    },
    /** 导出按钮操作 */
    async handleExport() {
      try {
        // 导出的二次确认
        await this.message.exportConfirm()
        // 发起导出
        this.exportLoading = true
        const data = await QuotationApi.exportQuotationExcel(Object.assign({}, this.queryParams))
        download.excel(data, '报价单.xlsx')
      } catch {
      } finally {
        this.exportLoading = false
      }
    },
    /** 提交表单审核操作 */
    async submitQuote(row) {
      const data = await this.message.prompt('请输入提交报价单的备注信息', '报价单提交');
      if (data?.action !== 'confirm') throw 'cancel'
      const parmas = {
        quoteNumber: row.quoteNumber,
        remark: data.value
      }
      const res = await QuotationApi.submitQuotation(parmas)
      if (res) {
        this.message.success('提交成功!')
        this.getList()
      } else {
        this.message.error('提交失败!')
      }
    },
    // 格式化日期
    handleDate(row: any) {
      return formatDate(row.createTime)
    },

    // 过滤状态数据
    async filterStatusData(realType: string) {
      if (realType) {
        await this.getList(false, STATUS[realType]);
        const filterData = this.list.filter((item: any) => {
          if (item.status == 40 || item.status == 10) {
            return true
          } else {
            return item.status == STATUS[realType]
          }
        })
        this.list = filterData
      }
    },
    statusChange(val: any) {
      this.selected = val
    },
    
    // 判断是否是管理员
    judgeAdmin() {
      const { wsCache } = useCache()
      const permissions = wsCache.get(CACHE_KEY.USER).permissions
      const all_permission = '*:*:*'
      const hasPermissions = permissions.some((permission: string) => {
        return permission == all_permission || permission.includes('quote:quotation:audit')
        // 这里逻辑是如果包含quotation:audit权限，那么就是管理员
      })
      return hasPermissions
    }
  }
}) 
</script>

<template>
  <div>
    <el-card shadow="never" class="mainCard">
      <div class="state flex flex-row w-[95%] gap-10 items-center">
        <el-card class="w-[17%] h-25 cursor-pointer" v-for="(item, index) in data" :key="index"
          :class="judgeAdmin() && item.status == '未提交' ? 'hidden' : ''" @click="filterStatusData(item.type)">
          <div class="stateBox flex flex-row justify-evenly items-center">
            <span class="iconfont" :class="`icon-${item.type}`"></span>
            <div class="info ">
              <span class="num block w-full text-3xl text-center">{{ item.count }}</span>
              <span class="desc block w-full text-center font-serif  ">{{ item.status }}</span>
            </div>
          </div>
        </el-card>
      </div>
      <div class=" flex items-center mx-8 hborder ">
        <el-button class="" size="large" type="primary" v-hasPermi="['quote:quotation:create']"
          @click="() => handleAdd('create')">新建报价单</el-button>
      </div>
    </el-card>
  </div>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <div class="headerWrap flex flex-row  items-center justify-between">
      <div class="titleBar flex flex-row items-center">
        <svg xmlns="http://www.w3.org/2000/svg" width="1.5em" height="1.5em" viewBox="0 0 24 24">
          <path fill="#aaa"
            d="M4.808 9.616q-.343 0-.576-.233T4 8.808V6.923q0-.343.232-.575t.576-.232h1.884q.343 0 .576.232t.232.575v1.885q0 .343-.232.575t-.576.233zm4.077 0q-.344 0-.576-.233q-.232-.232-.232-.575V6.923q0-.343.232-.575t.575-.232h10.308q.344 0 .576.232t.232.575v1.885q0 .343-.232.575t-.576.233zm0 3.923q-.344 0-.576-.233q-.232-.232-.232-.575V11q0-.343.232-.575q.232-.233.576-.233h10.307q.344 0 .576.232T20 11v1.73q0 .344-.232.576t-.576.233zm0 4.077q-.344 0-.576-.233q-.232-.232-.232-.575v-1.885q0-.343.232-.576t.575-.232h10.308q.344 0 .576.232q.232.233.232.576v1.885q0 .343-.232.575t-.576.233zm-4.077 0q-.344 0-.576-.233T4 16.808v-1.885q0-.343.232-.576t.576-.232h1.884q.343 0 .576.232q.232.233.232.576v1.885q0 .343-.232.575t-.576.233zm0-4.077q-.344 0-.576-.233T4 12.731V11q0-.343.232-.575t.576-.233h1.884q.343 0 .576.232T7.5 11v1.73q0 .344-.232.576t-.576.233z" />
        </svg>
        <span class="text-16px">报价单列表</span>
      </div>
      <el-form v-model="queryParams" class="flex flex-row items-center py-5 px-6  " ref="queryForm" size="small"
        :inline="true" v-show="showSearch" label-width="78px">
        <el-form-item label="" prop="date">
          <el-date-picker size="default" v-model="queryParams.orderDate" value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
        </el-form-item>
        <el-form-item label="" prop="status">
          <el-select v-model="queryParams.status" @change="statusChange" multiple collapse-tags-tooltip
            style="width: 220px" placeholder="请选择" size="default">
            <el-option v-for="(dict, index) in _getStrDictOptions(DICT_TYPE.QSD)" :label="dict.label"
              :value="dict.value" :key="index" />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="search">
          <el-input v-model="queryParams.search" size="default" style="width: 274px" placeholder="请输入项目名称/报价单编号/客户/责任人"
            clearable @keyup.enter="() => handleQuery()" />
        </el-form-item>
        <el-form-item>
          <el-button @click="() => handleQuery()" size="default">
            <Icon icon="ep:search" class="mr-5px" /> 搜索
          </el-button>
          <el-button size="default" @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> 重置
          </el-button>
          <el-button type="success" size="default" plain @click="handleExport" :loading="exportLoading"
            v-hasPermi="['quote:customer:export']">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table class="w-full" :header-cell-style="{ backgroundColor: '#f2f2f2', fontWeight: 700, color: '#909399' }"
      :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column align="left" type="index" label="序号" width="60" />
      <el-table-column align="left" label="" prop="id" width="30">
        <template #default="scope">
          <span class="hidden"></span>
        </template>
      </el-table-column>
      <el-table-column class=" text-xs" align="left" label="报价单编号" prop="quoteNumber" width="155" />
      <el-table-column align="left" label="项目名称" prop="projectName" width="220" />
      <el-table-column :formatter="handleDate" align="left" label="日期" prop="createTime" width="155">
      </el-table-column>
      <el-table-column align="left" label="客户" prop="customerName" width="220" />
      <el-table-column align="left" label="联系人" prop="customerContactPerson" width="80" />
      <!-- <el-table-column align="left" label="制作方" prop="selfName" width="180" /> -->
      <el-table-column align="left" label="责任人" prop="selfContactPerson" width="80" />
      <el-table-column align="left" label="状态" prop="status">
        <template #default="scope">
          <span class="  !font-600" v-if="scope.row.status == '0'">未提交</span>
          <span class="  !font-600" v-if="scope.row.status == '10'">审批中</span>
          <span class="  !font-600" v-if="scope.row.status == '20'">已通过</span>
          <span class="  !font-600" v-if="scope.row.status == '30'">已驳回</span>
          <span class="  !font-600" v-if="scope.row.status == '40'">退回中</span>
          <span class="  !font-600" v-if="scope.row.status == '50'">已退回</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="项目报价(未税)" prop="totalProductPrice" width="130">
        <template #default="scope">
          <span class="  !font-500">￥{{ _fomatCurrency(scope.row.totalProductPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="项目报价(含税)" prop="totalPrice" width="130">
        <template #default="scope">
          <span class="  !font-500">￥{{ _fomatCurrency(scope.row.totalPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="优惠价(含税)" prop="finalPrice" width="130">
        <template #default="scope">
          <span v-if="scope.row.finalPrice" class="  !font-500">￥{{ _fomatCurrency(scope.row.finalPrice) }}</span>
          <span v-else class="  !font-500">--</span>
        </template>
      </el-table-column>

      <!-- <el-table-column align="left" label="备注" prop="submitRemark" width="150" /> -->
      <el-table-column align="left" label="操作" width="210" fixed="right" prop="action">
        <template #default="scope">
          <el-button v-if="scope.row.status == '0'" link type="primary" @click="submitQuote(scope.row)">
            提交
          </el-button>
          <el-button v-hasPermi="['quote:quotation:audit']" v-if="scope.row.status == '10' || scope.row.status == '40'"
            link type="primary" @click="openForm('audit', scope.row)">
            审核
          </el-button>
          <el-button link type="primary" @click="openForm('detail', scope.row)">
            详情
          </el-button>
          <el-button link :type="scope.row.file > 0 ? 'primary' : 'warning'" v-if="scope.row.status == '20'"
            @click="openUploadForm('upload', scope.row)">
            {{ scope.row.file > 0 ? '已上传' : '附件上传' }}
          </el-button>
          <el-button link type="danger" v-hasPermi="['quote:quotation:delete']" primary
            @click="handleDelete(scope.row.id, scope.row.quoteNumber)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination class="myPagination" layout=" total, prev, pager, next, jumper," v-show="total > 0" :total="total"
      v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" @pagination="getList" />
    <!-- 对话框(添加 / 修改) -->
    <QuotationForm ref="formRef" @success="getList" />
    <uploadForm ref="uploadRef" @success="" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-overlay-dialog) {
  .uploadDialog {
    --el-dialog-margin-top: 23vh !important;
    --el-dialog-width: 75% !important;
    height: 60vh !important;
    overflow-y: scroll !important;

    .el-dialog__body {
      height: 80%;
    }
  }

}

:deep(.el-table__row--striped .el-table__cell) {
  background: #f2f2f2 !important;
}

:deep(.el-table__header) {
  .cell {
    font-weight: 900 !important;
    color: #101010 !important;
  }
}

:deep(.el-table__row) {
  .cell {
    font-family: Roboto, BlinkMacSystemFont, "Helvetica Neue", Arial, "Microsoft Yahei", "WenQuanYi Micro Hei", "Pingfang SC", sans-serif;
    font-weight: 400 !important;
    color: #101010 !important;
  }
}


:deep(.el-overlay-dialog) {
  overflow: hidden !important;
}

:deep(.el-dialog) {
  --el-dialog-margin-top: 0.5vh !important;
  --el-dialog-margin-bottom: 0.5vh !important;
  --el-dialog-width: 99% !important; //设置element-plus弹窗宽度
  height: 99vh !important;
  overflow-y: scroll !important;
  position: relative;

  .el-dialog__header {
    position: sticky;
    top: -10px;
    background-color: #fff;
    z-index: 999;
  }
}

.el-button--large {
  --el-button-size: 52px;
}

.mainCard {
  &> :deep(.el-card__body) {
    display: flex;
  }
}

.myPagination {
  width: 100%;

  &> :deep(.el-pagination__total) {
    flex: 1;
    color: #999;
    font-weight: bold;
  }


}

.hborder {
  position: relative;

  &::before {
    position: absolute;
    content: "";
    display: block;
    width: 2px;
    height: 76%;
    left: -40px;
    background-color: rgba(160, 159, 158, 0.4);
  }
}

.el-form-item {
  margin-bottom: 0;
}
</style>
